package com.hinnotek.warehouse.utils

import android.content.pm.PackageManager
import com.hinnotek.warehouse.BuildConfig
import com.lee.common.bean.VersionData
import com.lee.common.utils.InitUtils
import com.xuexiang.xupdate.entity.UpdateEntity
import com.xuexiang.xupdate.listener.IUpdateParseCallback
import com.xuexiang.xupdate.proxy.IUpdateParser
import com.xuexiang.xutil.net.JsonUtil

/**
 * 自定义更新解析器
 *
 * @author xuexiang
 * @since 2018/7/12 下午3:46
 */
class CustomUpdateParser : IUpdateParser {
    @Throws(Exception::class)
    override fun parseJson(json: String): UpdateEntity {
        return getParseResult(json)!!
    }

    private fun getParseResult(json: String): UpdateEntity? {


        val result = JsonUtil.fromJson(json, VersionData::class.java)

        val bean = result.data
        return if (result != null) {

            var versioncode = 1
            var versionName = ""
            val pm = InitUtils.context?.packageManager as PackageManager
            try {
                val packageInfo = pm.getPackageInfo("com.hinnotek.amoeba", 0);
                versioncode = packageInfo.versionCode;
                versionName = packageInfo.versionName;
            } catch (e: Exception) {
                e.printStackTrace();
            }

            val isIgn = bean.isUpdate == 0
            //val hasUp = bean.versionId > versioncode
            val hasUp = compareVersion(versionName, bean.versionNo) == -1
            //https://dl.coolapk.com/down?pn=com.coolapk.market&id=NDU5OQ&h=46bb9d98&from=from-web
            val updateContent = "版本更新"
            UpdateEntity()
                .setHasUpdate(hasUp)
                .setForce(isIgn)
                .setIsIgnorable(false)
                .setVersionCode(bean.versionId)
                .setVersionName(bean.versionNo)
                .setUpdateContent(updateContent)
                .setDownloadUrl(bean.loadPath)
        } else null
    }

    /**
     * 版本号比较
     * compareTo()方法返回值为int类型，就是比较两个值，如：x.compareTo(y)。如果前者大于后者，返回1，前者等于后者则返回0，前者小于后者则返回-1
     * @param oldVer
     * @param newVer
     * @return 范围可以是"2.20.", "2.10.0"  ,".20","2.10.0",2.1.3 ，3.7.5，10.2.0
     */
    private fun compareVersion(oldVer: String, newVer: String): Int {
        val s1Split = oldVer.split(".")
        val s2Split = newVer.split(".")
        val len1 = s1Split.size;
        val len2 = s2Split.size;
        val lim = len1.coerceAtMost(len2);
        var i = 0;
        while (i < lim) {
            val c1 = if ("" == s1Split[i]) 0 else s1Split[i].toInt()
            val c2 = if ("" == s2Split[i]) 0 else s2Split[i].toInt()
            if (c1 != c2) {
                return c1 - c2;
            }
            i++;
        }
        return len1 - len2;
    }

    @Throws(Exception::class)
    override fun parseJson(json: String, callback: IUpdateParseCallback) {
        //当isAsyncParser为 true时调用该方法, 所以当isAsyncParser为false可以不实现
        callback.onParseResult(getParseResult(json))
    }

    override fun isAsyncParser(): Boolean {
        return false
    }
}